<template>
  <div>
    <basic-container>
      <div class="el-page-header haruyuki-mb-20">
        <div
          class="el-page-header__left haruyuki-flex-center haruyuki-size-18"
          @click="goBack"
        >
          <i class="el-icon-arrow-left"></i>
          <div class="haruyuki-size-16">返回</div>
        </div>
        <div class="el-page-header__content">库存调拨</div>
      </div>
      <div class="haruyuki-flex-x-end haruyuki-mb-20">
        <el-button type="primary" size="small" icon="el-icon-upload2" plain @click="handleImport">批量调拨</el-button>
      </div>
      <stock-allot-form :store-form="stockForm" :stockType="stockType" ref="stockAllot"></stock-allot-form>
      <div class="haruyuki-flex-center">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleSave">添 加</el-button>
      </div>
      <avue-crud
        :option="option"
        :search.sync="search"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @sort-change="sortChange"
        @on-load="onLoad"
      >
      <!-- <template slot-scope="scope" slot="menu">
        <el-button
          v-if="permissionList.viewBtn"
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleDetail(scope.row, scope.index)"
          >详 情</el-button
        >
      </template> -->
      <template slot="menuLeft">
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
          >删 除
        </el-button>
      </template>
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.pos_info_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.pos_info_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
    </avue-crud>
    <div class="haruyuki-flex-center haruyuki-mt-20">
      <el-button type="primary" size="small" @click="submitStorage" :disabled="subDis">确认调拨</el-button>
      <el-button size="small" @click="goBack">取 消</el-button>
    </div>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
      :before-close="handleCloseExcel"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
      >
        <!-- :upload-after="uploadAfter" -->
        <template slot="inNo">
          <select-page :params="{serviceAuditStatus:2}" @update:select="serNoChange" ref="searchSerSelect" label="serviceName" value="serviceNo" :select.sync="excelForm.inNo" :url="website.searchLink.serviceUrl" placeholder-text="服务商" filter-key="searchParam"></select-page>
        </template>

        <template slot="excelFile">
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            :limit="1"
            :http-request="httpRequest"
            :on-success="onSuccess"
            :on-change="handleChange"
            :on-remove="handleRemove"
            multiple
            :file-list="fileList"
            :auto-upload="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">请上传 .xls,.xlsx 标准格式文件</div>
          </el-upload>
          <div style="display: flex; justify-content: flex-end;">
            <el-button type="primary" v-preventClick @click="uploadSubmit" :disabled="uploadDisabled" v-show="fileList.length">
              确定上传<i class="el-icon-upload2 el-icon--right"></i>
            </el-button>
          </div>
        </template>
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  allotStorage,
  queryTrList,
  uploadFileTr
  // remove
} from "@/api/rb-oem/store/store";
import {
  getExportTemplate,
} from "@/api/rb-oem/storeTransfer/store_transfer";
import stockAllotForm from '../components/stock_allot_form.vue';
import { downloadFileExcel } from "@/util/util";
import { mapGetters } from 'vuex'
import selectPage from "@/components/select-page/select-page";

let storeId = 1;
export default {
  components: {
    stockAllotForm,
    selectPage
  },
  data() {
    return {
      subDis:false,
      stockForm: {
        inNo: '',
        userNo: '',
        userNoServe: '',
        userNoServeName: '',
        belongTo: '',
        aisleCode: '',
        rptNo: '',//19
        rpsNo: '',
        rpmNo: '',
        rsSn: '',
        startSn: '',
        endSn: '',
        activeType: '',
        cardCode: '',
        qrCode: '',
        yxToken: '',
        simAmount:''
      },
      stockType: "",
      form: {},
      query: {},
      search: {},
      props: {
        //菜单权限数据 props
        label: "title",
        value: "key",
      },
      loading: false,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option:{},
      optionBase: {
        //height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        search: false,
        // columnBtn: false,
        addBtn: false,
        editBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "服务商编号",
            prop: "inNo",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "服务商名称",
            prop: "userName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备归属",
            // prop: "belongTo",
            prop: "belongToName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "通道名称",
            prop: "aisleName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备类型",
            // prop: "rptNo",
            prop: "rptName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备品牌",
            // prop: "rpsNo",
            prop: "rpsName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备型号",
            // prop: "rpmNo",
            prop: "rpmName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备编号",
            prop: "rsSn",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "二维码编号",
            prop: "qrCode",
            slot: true,
            display: false,
            overHidden: true,
          },
          // {
          //   label: "活动类型",
          //   prop: "activeType",
          //   slot: true,
          //   display: false,
          //   overHidden: true,
          // },
          {
            label: "活动类型",
            prop: "activeName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "音响密钥",
            prop: "yxToken",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "物联网卡编号",
            prop: "cardCode",
            slot: true,
            display: false,
            overHidden: true,
          },
        ],
      },
      optionPos: {
        //height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        search: false,
        // columnBtn: false,
        addBtn: false,
        editBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "服务商编号",
            prop: "inNo",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "服务商名称",
            prop: "userName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备归属",
            // prop: "belongTo",
            prop: "belongToName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "通道名称",
            prop: "aisleName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备类型",
            // prop: "rptNo",
            prop: "rptName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备品牌",
            // prop: "rpsNo",
            prop: "rpsName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备型号",
            // prop: "rpmNo",
            prop: "rpmName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "设备编号",
            prop: "rsSn",
            slot: true,
            display: false,
            overHidden: true,
          },
          // {
          //   label: "活动类型",
          //   prop: "activeType",
          //   slot: true,
          //   display: false,
          //   overHidden: true,
          // },
          {
            label: "活动类型",
            prop: "activeName",
            slot: true,
            display: false,
            overHidden: true,
          },
          {
            label: "流量卡金额",
            prop: "simAmount",
            slot: true,
            display: false,
            overHidden: true,
          }
        ],
      },
      data: [],
      awaitData: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "服务商",
            prop: "inNo",
            type: "select",
            span: 24,
            // remote: true,
            // filterable: true,
            // clearable: true,
            // props: {
            //   label: "serviceName",
            //   value: "serviceNo",
            //   desc: "serviceNo"
            // },
            // dicUrl: "/api/rb-oem/oem/serviceInfo/service_info/list?current=1&size=10&serviceAuditStatus=2&isSelectDirect=1&serviceName={{key}}",
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            // change: ({value}) => {
            //   if (value) {
            //     const column = this.findObject(this.excelOption.column, "excelFile");
            //     column.data.inNo = value;
            //   } else {
            //     const column = this.findObject(this.excelOption.column, "excelFile");
            //     column.data.inNo = '';
            //   }
            // }
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
              url:'link',
              name:'originalName',
            },
            data: {
              inNo: ''
            },
            headers: {
              "Content-Type": "multipart/form-data"
            },
            tip: "请选择服务商上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-oem/oem/store/store/importTr",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      uploadDisabled:false,
      fileList:[]
    };
  },
  computed: {
    ...mapGetters(['tag', 'userInfo', 'permission']),
  },
  watch: {
    "$route.query.e": {
      handler(val) {
        if (val) {
          const param = JSON.parse(this.$crypto.decrypt(val));
          const { rptNo, stockType } = param;
          this.stockType = stockType;
          if (rptNo) { //设备类型 默认值 19 音响 | 20 传统POS
            this.stockForm.rptNo = rptNo;
            if (this.stockForm.rptNo == '20') {
              this.option = this.optionPos;
            } else {
              this.option = this.optionBase;
            }
          } else {
            this.stockForm.rptNo = '19';
            this.option = this.optionBase;
          }
        }
      },
      immediate: true,
    }
  },
  created() {
  },
  methods: {
    // 批量上传-选择服务商
    serNoChange(value){
      if (value) {
        const column = this.findObject(this.excelOption.column, "excelFile");
        column.data.inNo = value;
      } else {
        const column = this.findObject(this.excelOption.column, "excelFile");
        column.data.inNo = '';
      }
    },
    /**
     * @func 提交入库
     * @desc 提交入库
     * */
    submitStorage() {
      this.subDis = true;
      allotStorage({dto:this.awaitData}).then(
        () => {
          // this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "调拨成功!",
          });
          this.handleCloseTag();
          // this.goBack();
        },
        (error) => {
          window.console.log(error);
          this.subDis = false;
        }
      );
    },
    /**
     * @func 添加待入库
     * @desc 添加至待入库列表 可批量添加
     * */
    handleSave() {
      this.$refs["stockAllot"].$refs["storeForm"].validate((valid) => {
        if (valid) {
          queryTrList(this.stockForm).then(
            (res) => {
              let storeData = res.data.data;
              if (this.data.length > 0) {
                // 首先构造Object
                const idSet = this.data.reduce((acc, v) => {
                    acc[v.rsSn] = true;
                    return acc;
                }, {});
                //去重后的result
                const result = storeData.filter(v => !idSet[v.rsSn]);
                if (result.length > 0) {
                  for (let i = 0; i < result.length; i++) {
                    this.awaitData.unshift({id: storeId++, ...result[i]});
                  }
                } else {
                  this.$message({
                    type: "warning",
                    message: "所输入的设备编号相同!",
                  });
                }
                // console.log(result, 'result');
              } else {
                for (let i = 0; i < storeData.length; i++) {
                  this.awaitData.unshift({id: storeId++, ...storeData[i]});
                }
              }
              this.onLoad();
            },
            (error) => {
              window.console.log(error);
            }
          );
        } else {
          return false;
        }
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // return remove(this.ids);
          for (let k = 0; k < this.selectionList.length; k++) {
            this.data.splice(
                this.data.findIndex(
                  item => item.id === this.selectionList[k].id
                ),
                1
            );
          }
        })
        .then(() => {
          // this.onLoad();
          this.awaitData = this.data;
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // return remove(row.id);
          this.data.splice(row.$index, 1);
          this.awaitData = this.data;
        })
        .then(() => {
          // this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleTemplate() {
      getExportTemplate().then((res) => {
          downloadFileExcel(res);
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    uploadSubmit(){
      this.$refs.upload.submit();
    },
    /* 关闭弹框 */
    handleCloseExcel(done){
      this.excelForm = {};
      this.excelForm.inNo = '';
      this.fileList =[];
      done();
    },
    /* 批量文件上传 */
    httpRequest(option){
      this.uploadDisabled = true ;
      uploadFileTr(option.file, option.file.name,this.excelForm.inNo).then((res) => {
        this.uploadDisabled = false ;
        this.$message({ type: "success", message: res.data.msg });
        this.refreshChange();
      },() =>{
        this.uploadDisabled = false ;
      })
    },
    // uploadAfter(res, done) {
    //   if (res) {
    //     if (res.link) {
    //       //   window.open(res.link, res.originalName);
    //     }
    //   }
    //   this.refreshChange();
    //   done();
    // },
    refreshChange() {
      this.excelBox = false;
      this.excelForm = {};
      this.excelForm.inNo = '';
      this.fileList =[];
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    onLoad() {
      this.loading = true;
      if (this.awaitData.length > 0) {
        //awaitData为全部数据，data是目前表格绑定的数据
        this.data = this.awaitData.slice(
          (this.page.currentPage - 1) * this.page.pageSize,
          this.page.currentPage * this.page.pageSize
        );
        this.page.total = this.awaitData.length;
      }
      this.loading = false;
      // getList(
      //   page.currentPage,
      //   page.pageSize,
      //   page.serviceKind,
      //   Object.assign(params, this.query)
      // ).then((res) => {
      //   const data = res.data.data;
      //   this.page.total = data.total;
      //   this.data = data.records;
      //   this.loading = false;
      //   this.selectionClear();
      // });
    },
    // 关闭当前tag，并跳转
    handleCloseTag() {
      this.$store.commit('DEL_TAG', this.tag)
      this.$router.push({
        // name: '仓库管理',
        path: '/rb-oem/store/store',
        params: {
          id: 1,
        },
      })
    },
    /**
     * @func 返回页面
     * @desc 返回页面 goBack
     * */
    goBack() {
      this.$router.$avueRouter.closeTag();
      this.$router.back();
    },
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-select{
  width: 100%;
}
</style>